'''
    小罐茶   xgc=token=xxx;sid=xxx@token=xxx;sid=xxx
'''

import datetime
import json
import os
import pprint
import random
import time
import requests
import hashlib


def get_nonce():
    """
        生成一个指定长度的随机字符串
        """
    randomlength = 16
    random_str = ''
    base_str = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    length = len(base_str) - 1
    for i in range(randomlength):
        random_str += base_str[random.randint(0, length)]
    # print(random_str)
    return random_str


def genHeader(data):
    timestamp = time.time()
    return {
        'content-type': 'application/json',
        'Extra-Data': f'{{"is_weapp":1,"sid":"{data.get("sid")}","version":"2.154.3.101","client":"weapp","bizEnv":"wsc","uuid":"LgzICUpbvGKRHhn1708472028047","ftime":{timestamp}}}',
        'Accept-Encoding': 'gzip,compress,br,deflate',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.29(0x18001d38) NetType/4G Language/zh_CN'
    }


def signIn(data, header, index):
    try:
        url = f'https://h5.youzan.com/wscump/checkin/checkinV2.json?checkinId=18201&app_id=wx8d2db6a4b7580eeb&kdt_id=14224644&access_token={data.get("token")}'
        response = requests.get(url=url, headers=header).json()
        print(f'第{index}个账号 签到返回: {response}')
        return f'第{index}个账号 签到返回: {response}'
    except Exception as e:
        return f'第{index}个账号 签到异常 {e}'


def webhook(message, webhookToken):
    url = f'http://www.pushplus.plus/send'
    headers = {
        'Content-Type': 'application/json'
    }
    data = {
        "token": webhookToken,
        "title": "小罐茶",
        "content": message,
        "template": "json"
    }
    response = requests.post(url=url, data=json.dumps(data), headers=headers).json()
    print(f"推送成功")


def genEnvs():
    cks = os.environ['xgc']
    cks = cks.split('@')
    tokenArr = []
    for ck in cks:
        cks1 = ck.split(';')
        obj = {}
        for s in cks1:
            arr2 = s.split('=')
            obj[arr2[0]] = arr2[1]
        tokenArr.append(obj)
    return tokenArr


def sleepmoment(num):
    random_seconds = random.randint(1, num)
    print(f'休眠{random_seconds}秒')
    time.sleep(random_seconds)


if __name__ == '__main__':
    print('开始执行...')
    sleepmoment(10)
    tokenArray = genEnvs()
    length = len(tokenArray)
    print(f'读取到{length}个账号')
    webhookToken = os.environ['PUSH_PLUS_TOKEN']
    msg = ""
    for index, ck in enumerate(tokenArray):
        header = genHeader(ck)
        print(f'第{index + 1}个账号 开始签到')
        msg += signIn(ck, header, index + 1)
        sleepmoment(2)

    webhook(msg, webhookToken)
